﻿using System;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;
using Tool.Common;
using Tool.ImageHelper;
using Tool.Web.HttpHelper;

namespace Core.Expansion
{
	public static class String
	{
		static readonly object obj = new object();

		internal static string HandleImagePath(this string image)
		{
			return image.Replace(AppDomain.CurrentDomain.BaseDirectory + "data\\image\\", "");
		}

		internal static string HandleImage(this string image, bool IsR18 = false)
		{
			try
			{
				string text = Path.GetDirectoryName(image) + "\\temp\\";
				string text3 = string.Empty;
				if (!Directory.Exists(text))
				{
					Directory.CreateDirectory(text);
				}
				if (new FileInfo(image).Length / 1024 > 2048)
				{
					lock (obj)
					{
						text3 = text + TimeHelp.GetCurrentTimeUnix(IsMilliseconds: true).ToString() + ".jpg";
					}
					if (ImageHelp.CompressImage(image, text3, false, 90)) image = text3;
				}
				if (IsR18)
				{
					if (string.IsNullOrEmpty(text3))
					{
						string text2;
						lock (obj)
						{
							text2 = text + TimeHelp.GetCurrentTimeUnix(IsMilliseconds: true).ToString() + ".jpg";
						}
						ImageHelp.ChangeMD5(image, text2);
						return text2;
					}
					else ImageHelp.ChangeMD5(image, image);
				}
				return image;
			}
			catch (Exception)
			{
				return image;
			}
		}

		public static string Translate(this string text, string sl = "auto", string tl = "zh-CN")
		{
			//http://translate.google.cn/translate_a/single?client=gtx&sl=auto&tl=zh-CN&dt=t&q=Hello&ie=UTF-8
			//[[["你好","Hello",null,null,1]
			var data = Encoding.UTF8.GetString(HttpNet.Get($"http://translate.google.cn/translate_a/single?client=gtx&sl={sl}&tl={tl}&dt=t&q={Url.Encode(text, Encoding.UTF8)}&ie=UTF-8"));
			var json = JArray.Parse(data);
			StringBuilder stringBuilder = new StringBuilder(text.Length);
			foreach (var item in json[0])
			{
				stringBuilder.Append(item[0]);
			}
			return stringBuilder.ToString();
		}
	}
}